package com.ybkj.daijia.api.apirest;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.WxSetting;
import com.ybkj.daijia.api.beatpay.utils.BestPayCreateOrder;
import com.ybkj.daijia.api.beatpay.utils.BestPayOrderModel;
import com.ybkj.daijia.api.beatpay.utils.CryptTool;
import com.ybkj.daijia.api.member.alipay.config.AlipayConfig;
import com.ybkj.daijia.api.member.alipay.sign.MemberOrderSign;
import com.ybkj.daijia.api.member.alipay.sign.RSA;
import com.ybkj.daijia.api.member.alipay.util.AlipayNotify;
import com.ybkj.daijia.api.unionpay.AcpService;
import com.ybkj.daijia.api.unionpay.DemoBase;
import com.ybkj.daijia.api.unionpay.LogUtil;
import com.ybkj.daijia.api.unionpay.SDKConfig;
import com.ybkj.daijia.api.unionpay.SDKConstants;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.api.weixin.tenpayv3.Configuration;
import com.ybkj.daijia.api.weixin.tenpayv3.GetWxOrderno;
import com.ybkj.daijia.api.weixin.tenpayv3.RequestHandler;
import com.ybkj.daijia.api.weixin.tenpayv3.Sha1Util;
import com.ybkj.daijia.api.weixin.tenpayv3.TenpayUtil;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.errand.SelectPrice;
import com.ybkj.daijia.server.event.model.OrderPassengerHasPayEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderAcceptEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderArriveEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderCancelEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderConfirmEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderCreateEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderRecordEvent;
import com.ybkj.daijia.server.freight.Order;
import com.ybkj.daijia.server.freight.Order.PayTypeDetails;
import com.ybkj.daijia.server.freight.PayRecordOrder;
import com.ybkj.daijia.server.freight.PayRecordOrder.PayRecordTypeOrder;
import com.ybkj.daijia.server.freight.Truck;
import com.ybkj.daijia.server.freight.TruckType;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.ChargeStartDistance;
import com.ybkj.daijia.server.model.ChargeStartTime;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverRefuseRecord;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.sales.CouponRule.CouponType;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.DriverRefuseRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("ApiFreightProcessController")
@RequestMapping(value = "api/freight/")
public class FreightProcessController {

    private static final Logger logger = LoggerFactory.getLogger(FreightProcessController.class);
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private FreightService freightService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private DriverRefuseRecordService driverRefuseRecordService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private SmsService smsService;

    /**
     * 获取请求参数中所有的信息.
     *
     * @param request
     * @return
     */
    public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                // 在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

    /**
     * 根据距离和时间按照公司的收费标准预估订单价格
     *
     * @param passengerId
     * @param companyId
     * @param time
     * @param mileage
     * @return
     */
    @RequestMapping(value = "getPrice", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> getPrice(@RequestParam("areaId") Long areaId,
        @RequestParam("mileage") Double mileage1, @RequestParam("time") Long time1) {
        Map<String, Object> result = new HashMap<String, Object>();
        BigDecimal money = BigDecimal.ZERO;
        try {
            Area area = areaService.findOneWithCharge(areaId);
            SelectPrice selectPrice = new SelectPrice();
            if (null != area) {
                selectPrice.setPrice(time1, mileage1, area, null, 0D);
            } else {
                result.put("success", false);
                result.put("message", "收费标准不存在");
                return result;
            }
            money = selectPrice.shouldCash;
            BigDecimal startPrice = selectPrice.qbCost;
            BigDecimal mileagePrice = selectPrice.disCost;
            BigDecimal travelTimePrice = selectPrice.travalTimeCost;
            ChargeStartTime price = selectPrice.getPrice();
            StringBuilder builder = new StringBuilder();
            builder.append("起步价:" + startPrice + "元\n");
            List<ChargeStartDistance> distances = price.getChargeStartDistances();

            if (distances != null && distances.size() != 0) {
                for (ChargeStartDistance d : distances) {
                    builder.append(
                        d.getStartdistance() + "公里到" + d.getDistance() + "公里内,加收" + d.getMoney()
                            + "元");
                    builder.append("\n");
                }
            }

            builder.append("超过" + price.getQblc() + "公里");
            builder.append("以后每" + price.getDjglUnit() + "公里");
            builder.append("加收" + price.getDjglCost() + "元");
            if (price.getDjglThresholdt() != 0) {
                builder.append("(不足" + price.getDjglThresholdt() + "公里不计费)");
            }
            builder.append("\n");
            builder.append("起步后" + price.getQbsj() + "分钟内不收费");
            builder.append("以后每" + price.getDjsjUnit() + "分钟");
            builder.append("加收" + price.getDjsjCost() + "元");
            if (price.getDjsjThresholdt() != 0) {
                builder.append("(不足" + price.getDjsjThresholdt() + "分钟不收费)");
            }
            builder.append("\n");
            builder.append("免费等候" + price.getMfdhsj() + "分钟");
            BigDecimal bigDecimal = price.getDhsjAtonceCost();

            if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
                builder.append("到达则立即加收" + price.getDhsjAtonceCost() + "元");
            }
            builder.append("后每" + price.getDhsjUnit() + "分钟");
            builder.append("加收" + price.getDhsjCost() + "元");
            if (price.getDhsjThresholdt() != 0) {
                builder.append("(低于" + price.getDhsjThresholdt() + "分钟不计费)");
            }
            builder.append("\n");
            if (StringUtils.isNotBlank(area.getMemo())) {
                builder.append("备注:" + area.getMemo());
            }
            result.put("success", true);
            result.put("message", "请求成功");
            result.put("pay_detail", builder.toString());
            result.put("money", money != null ? money : 0.0);
            result.put("startPrice", startPrice != null ? startPrice : 0.0); // 起步价
            result.put("mileagePrice", mileagePrice != null ? mileagePrice : 0.0); // 行驶里程费用
            result
                .put("travelTimePrice", travelTimePrice != null ? travelTimePrice : 0.0); // 服务时间费用
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "请求失败");
            return result;
        }

    }

    /**
     * 查询货车类型
     *
     * @param acKey
     * @param appKey
     * @param lng
     * @param lat
     * @return
     */
    @RequestMapping(value = "findTruckType", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> findTruckType(
        @RequestParam(value = "acKey", required = false) String ack,
        @RequestParam("lng") Double lng,
        @RequestParam("lat") Double lat) {

        Long companyId = null;

        if (StringUtils.isNotBlank(ack)) {
            Company ackCompany = companyService.findByAppKey(ack);
            if (null != ackCompany) {
                companyId = ackCompany.getId();
            }
        }

        if (null == companyId) {

            String city = "";
            int i = 0;
            while (i <= 4) {
                city = HttpClientUtil.getCityByLngAndLat(lng, lat);
                if (StringUtils.isNotBlank(city)) {
                    break;
                }
                i++;
            }
            List<Company> list = companyService.findByAreaCityName(city);
            if (!CollectionUtils.isEmpty(list)) {

                List<Company> notMainCompanys = new ArrayList<Company>();
                Company cityMainCompany = null;

                for (Company c : list) {
                    if (!c.isCompanyType()) {
                        if (StringUtils.isBlank(c.getAppKey())) {
                            notMainCompanys.add(c);
                        }
                    } else {
                        cityMainCompany = c;
                    }
                }

                if (null == companyId) {
                    if (!CollectionUtils.isEmpty(notMainCompanys)) {
                        companyId = notMainCompanys
                            .get(new Random().nextInt(notMainCompanys.size())).getId();
                    }
                }

                if (null == companyId) {
                    if (null != cityMainCompany) {
                        companyId = cityMainCompany.getId();
                    }
                }

            }
            if (null == companyId) {
                companyId = companyService.getMain().getId();
            }
        }

        Map<String, Object> carTypesMapList = new HashMap<String, Object>();
        try {
            List<TruckType> carTypes = freightService.queryTruckTypes(companyId);
            carTypesMapList.put("code", 0);
            carTypesMapList.put("message", "成功");
            carTypesMapList.put("data", carTypes);

        } catch (Exception e) {
            carTypesMapList.put("code", 500);
            carTypesMapList.put("message", "查询失败");
            logger.error("findTruckType error : " + e.getMessage());
        }

        return carTypesMapList;
    }

    /**
     * 查询当前位置的司机
     *
     * @param lng
     * @param lat
     * @param truckTypeId
     * @param appKey
     * @return
     */
    @RequestMapping(value = "findDrivers", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> findDrivers(@RequestParam("lng") Double lng,
        @RequestParam("lat") Double lat, @RequestParam("truckTypeId") Long truckTypeId) {
        List<Driver> list = driverService.queryNearFreightDrivers(lng, lat);
        List<Map<String, Object>> maps = new LinkedList<Map<String, Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        for (Driver driver : list) {
            if (driver.getTruckId() != null) {
                Truck truck = freightService.findTruck(driver.getTruckId());
                if (truck != null && truck.getTruckTypeId().equals(truckTypeId)) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("address", driver.getAddress());
                    map.put("carNumber", truck.getCarNumber());
                    if (driver.getLastLatitude() == null || driver.getLastLatitude() == null) {
                        map.put("lng", driver.getLongitude());
                        map.put("lat", driver.getLatitude());
                    } else {
                        map.put("lng", driver.getLastLongitude());
                        map.put("lat", driver.getLastLatitude());
                    }
                    maps.add(map);
                }

            }

        }
        map1.put("code", 0);
        map1.put("message", "成功");
        map1.put("data", maps);
        return map1;
    }

    @RequestMapping(value = "queryTruckType", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> queryTruckType(@RequestParam("companyId") Long companyId) {
        Map<String, Object> carTypesMapList = new HashMap<String, Object>();
        try {
            List<TruckType> carTypes = freightService.queryTruckTypes(companyId);
            carTypesMapList.put("code", 0);
            carTypesMapList.put("message", "成功");
            carTypesMapList.put("data", carTypes);
        } catch (Exception e) {
            carTypesMapList.put("code", 500);
            carTypesMapList.put("message", "查询失败");
            logger.error("findTruckType error : " + e.getMessage());
        }

        return carTypesMapList;
    }

    /*
     * @RequestMapping(value = "findDriverByLngAndLat", method =
     * RequestMethod.GET)
     *
     * @ResponseBody public List<Map<String,Object>> findDriverByLngAndLat(Double
     * lng ,Double lat,Long truckTypeId){ List<Driver> list =
     * driverService.queryNearFreightDrivers(lng, lat); List<Map<String,Object>>
     * maps = new LinkedList<Map<String,Object>>();
     *
     * for(Driver driver : list){ Map<String,Object> temp = new HashMap<String,
     * Object>(); if(driver.getTruckId()!=null){ Truck truck =
     * freightService.findTruck(driver.getTruckId());
     * if(truck.getTruckTypeId().equals(truckTypeId)){
     * if(driver.getLastLatitude()==null||driver.getLastLatitude()==null){
     * temp.put("driverId", driver.getId()); temp.put("lng",
     * driver.getLongitude()); temp.put("lat", driver.getLatitude());
     * temp.put("address", driver.getAddress()); temp.put("truckId",
     * driver.getTruckId()); }else{ temp.put("driverId", driver.getId());
     * temp.put("lng", driver.getLastLongitude()); temp.put("lat",
     * driver.getLastLatitude()); temp.put("address", driver.getCurrentAddress());
     * temp.put("truckId", driver.getTruckId()); } maps.add(temp);
     *
     * } }
     *
     * }
     *
     *
     * return maps;
     *
     * }
     */

    /*
     * @RequestMapping(value = "findDriverById", method = RequestMethod.GET)
     *
     * @ResponseBody public Map<String,Object> findDriverById(Long driverId){
     * Map<String,Object> map = null; Driver driver =
     * driverService.findOne(driverId); if(driver!=null){ map = new
     * HashMap<String, Object>(); map.put("employNo", driver.getUsername());
     * map.put("phone",driver.getPhone()); map.put("employScore",
     * driver.getStarLevel());
     * if(driver.getLastLatitude()==null||driver.getLastLatitude()==null){
     * map.put("lng", driver.getLongitude()); map.put("lat",
     * driver.getLatitude()); map.put("address", driver.getAddress()); }else{
     * map.put("lng", driver.getLastLongitude()); map.put("lat",
     * driver.getLastLatitude()); map.put("address", driver.getCurrentAddress());
     * } } return map;
     *
     * }
     */

    /**
     * 查询指定司机位置
     *
     * @param driverId
     * @param appKey
     * @return
     */
    @RequestMapping(value = "findDriverById", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findDriverById(@RequestParam("driverId") Long driverId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        try {
            Driver driver = driverService.findOne(driverId);
            map = new HashMap<String, Object>();
            map.put("employNo", driver.getUsername());
            map.put("phone", driver.getPhone());
            map.put("employScore", driver.getStarLevel());
            if (driver.getLastLatitude() == null || driver.getLastLatitude() == null) {
                map.put("lng", driver.getLongitude());
                map.put("lat", driver.getLatitude());
                map.put("address", driver.getAddress());
            } else {
                map.put("lng", driver.getLastLongitude());
                map.put("lat", driver.getLastLatitude());
                map.put("address", driver.getCurrentAddress());
            }
            if (driver.getTruckId() != null) {
                Truck truck = freightService.findTruck(driver.getTruckId());
                map.put("carNumber", truck.getCarNumber());
            } else {
                map.put("carNumber", "无");
            }

            map1.put("code", 0);
            map1.put("message", "成功");
            map1.put("data", map);
        } catch (Exception e) {
            e.printStackTrace();
            map1.put("code", 500);
            map1.put("message", "内部服务器错误");
        }
        return map1;
    }

    // 显示催单记录
    @RequestMapping(value = "hurryOrder")
    public @ResponseBody
    Map<String, Object> hurryOrder(Long orderId) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Company orderCompany = null;
            Order order = freightService.findOne(orderId);
            if (null != order) {
                orderCompany = companyService.findOne(order.getCompanyId());
                if (null != orderCompany) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("passengerName", order.getPassengerName());
                    jsonObject.put("passengerPhone", order.getPassengerPhone());
                    jsonObject.put("orderId", order.getId());
                    jsonObject.put("id", order.getId());
                    jsonObject.put("orderNo", order.getOrderNo());
                    jsonObject.put("status", order.getStatus());
                    jsonObject.put("startAddress", order.getStartAddress());
                    jsonObject.put("startLat", order.getStartLat());
                    jsonObject.put("startLng", order.getStartLng());
                    jsonObject.put("type", "hurryfreightOrder_company");
                    Company mainCompany = companyService.getMain();
                    WebSocketSend
                        .boardcastToCompany(jsonObject, orderCompany.getId(), mainCompany.getId());
                    map.put("success", true);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping(value = "pushNewOrder")
    public @ResponseBody
    Result<Object> pushNewOrder(Long orderId) {
        try {
            Order order = freightService.findOne(orderId);
            FreightOrderCreateEvent freightOrderCreateEvent = new FreightOrderCreateEvent(order);
            applicationEventMulticaster.multicastEvent(freightOrderCreateEvent);

            FreightOrderRecordEvent orderRecordEvent = new FreightOrderRecordEvent(order);
            applicationEventMulticaster.multicastEvent(orderRecordEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<Object>(true, "成功");
    }

    @RequestMapping(value = "pushOrderAccept")
    public @ResponseBody
    Result<Object> pushOrderAccept(Long orderId, Long employId) {
        try {
            Order order = freightService.findOne(orderId);
            Driver driver = driverService.findOne(employId);
            driverService
                .updateStatusAndJobStatus(Driver.DRIVER_BUSY, Driver.DRIVER_JOBSTATUS_FREIGHT,
                    order.getEmployId());

            FreightOrderAcceptEvent freightOrderAcceptEvent = new FreightOrderAcceptEvent(order,
                driver);
            applicationEventMulticaster.multicastEvent(freightOrderAcceptEvent);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<Object>(true, "成功");
    }

    @RequestMapping(value = "pushOrderCancel")
    public @ResponseBody
    Result<Object> pushOrderCancel(Long orderId, Boolean isDriver) {
        if (isDriver == null) {
            isDriver = false;
        }
        try {

            Order order = freightService.findOne(orderId);
            if (order.getEmployId() != null) {
                Driver dr = driverService.findOne(order.getEmployId());
                if (dr.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService.updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, dr.getId());
                }
            }
            if (isDriver) {
                FreightOrderCancelEvent freightOrderCancelEvent = new FreightOrderCancelEvent(order,
                    null,
                    "driverCancel");
                applicationEventMulticaster.multicastEvent(freightOrderCancelEvent);
            } else {
                Driver driver = driverService.findOne(order.getEmployId());
                FreightOrderCancelEvent freightOrderCancelEvent = new FreightOrderCancelEvent(order,
                    driver, "customerCancel");
                applicationEventMulticaster.multicastEvent(freightOrderCancelEvent);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<Object>(true, "成功");
    }

    @RequestMapping(value = "pushWait")
    public @ResponseBody
    Result<Object> pushWait(Long passengerId, Long orderId) {
        Order order = freightService.findOne(orderId);

        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        try {
            FreightOrderArriveEvent freightOrderArriveEvent = new FreightOrderArriveEvent(order,
                passenger);
            applicationEventMulticaster.multicastEvent(freightOrderArriveEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<Object>(true, "成功");
    }

    @RequestMapping(value = "pushRefuseOrder")
    public void pushRefuseOrder(Long orderId, Long employId, String cause) {
        try {
            if (null != orderId) {
                Order order = freightService.findOne(orderId);
                if (null != order) {
                    Driver driver = driverService.findOne(employId);
                    if (null != driver) {
                        driverService
                            .updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                        // 拒绝工单记录
                        DriverRefuseRecord driverRefuseRecord = new DriverRefuseRecord();
                        driverRefuseRecord.setEmployId(driver.getId());
                        driverRefuseRecord.setEmployRealName(driver.getRealname());
                        driverRefuseRecord.setEmployUserName(driver.getUsername());
                        driverRefuseRecord.setEmployPhone(driver.getPhone());
                        driverRefuseRecord.setHappend(new Date());
                        driverRefuseRecord.setOrderId(order.getId());
                        driverRefuseRecord.setOrderNumber(order.getOrderNo());
                        driverRefuseRecord.setOrderCompanyId(order.getCompanyId());
                        driverRefuseRecord.setMemo(cause);
                        driverRefuseRecord.setOrderType(DriverRefuseRecord.OrderType.freight);
                        driverRefuseRecordService.save(driverRefuseRecord);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("push error : " + e.getMessage());
        }
    }

    /**
     * 设置为空闲状态
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "updateDriver")
    public @ResponseBody
    Map<String, Object> updateDriver(Long orderId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        Order order = freightService.findOne(orderId);

        if (order != null && order.getEmployId() != null) {
            Driver driver = driverService.findOne(order.getEmployId());
            if (null != driver) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService
                        .updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                }
                map.put("success", true);
            }
        }
        return map;
    }

    /**
     * 修改司机为忙碌状态
     *
     * @param driverId
     * @return
     */
    public @ResponseBody
    Map<String, Object> updateBusyDriver(Long driverId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        Driver driver = driverService.findOne(driverId);
        if (null != driver) {
            if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                driverService
                    .updateStatusAndJobStatus(Driver.DRIVER_BUSY, Driver.DRIVER_JOBSTATUS_FREIGHT,
                        driver.getId());
            }
            map.put("success", true);
        }
        return map;
    }

    @RequestMapping(value = "listValidCouponsByPassenger", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> listValidCouponsByPassenger(Long passengerId) {

        Map<String, Object> map = new HashMap<String, Object>();

        List<Map<String, Object>> couponMapList = new ArrayList<Map<String, Object>>();

        List<Coupon> coupons = couponService
            .listByPassenger(passengerId, CouponType.freight, null, null);
        if (!CollectionUtils.isEmpty(coupons)) {
            for (Coupon coupon : coupons) {
                CouponRule rule = coupon.getCouponRule();
                Map<String, Object> couponMap = new HashMap<String, Object>();
                couponMap.put("couponId", coupon.getId());
                couponMap.put("couponType", rule.getType());
                couponMap.put("couponMoney", rule.getMoney());
                couponMap.put("couponDiscount", rule.getDiscount());
                couponMap.put("couponCode", coupon.getCode());
                couponMap.put("couponTitle", rule.getTitle());
                couponMap.put("startTime", rule.getStart().getTime());
                if (null != rule.getEnd()) {
                    couponMap.put("endTime", rule.getEnd().getTime());
                } else {
                    couponMap.put("endTime", null);
                }
                couponMapList.add(couponMap);
            }
        }

        map.put("code", 0);
        map.put("data", couponMapList);
        map.put("msg", "成功");
        return map;
    }

    @RequestMapping(value = "completeTaskData", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> completeTask(Long orderId) {

        logger.error("recv orderId:{}", orderId);

        Map<String, Object> map = new HashMap<String, Object>();

        Order order = freightService.findOne(orderId);

        if (null == order) {
            map.put("success", false);
            map.put("message", "订单不存在");
            return map;
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
            map.put("success", false);
            map.put("message", "订单状态不正确");
            return map;
        }

        Driver driver = driverService.findOne(order.getEmployId());
        if (null == driver) {
            map.put("success", false);
            map.put("message", "订单服务人员不存在");
            return map;
        }
        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        if (null == passenger) {
            map.put("success", false);
            map.put("message", "订单客户不存在");
            return map;
        }

        try {
            map.put("orderId", order.getId());
            map.put("orderNumber", order.getOrderNo());
            map.put("orderType", "freight");
            map.put("passengerPhone", passenger.getPhone());
            map.put("passengerName", passenger.getName());
            map.put("passengerType", passenger.getTypeStr());

            // 等级
            map.put("passengerGrade", passenger.getGrade_name());

            Company orderCompany = companyService.findOne(order.getCompanyId());
            map.put("orderCompanyName", orderCompany.getAbbreviation());

            Company passengerCompany = companyService.findOne(passenger.getCompanyId());
            map.put("passengerCompanyName", passengerCompany.getAbbreviation());

            if (passenger.getType() == Passenger.TYPE_PASSENGER) {
                map.put("overdraw", passenger.isAllowOverdraw());
                map.put(
                    "virtual",
                    passenger.getDrawMoney().add(passenger.getNodrawMoney())
                        .setScale(2, BigDecimal.ROUND_HALF_UP));
            } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
                Enterprise enterprise = memberService
                    .findOneEnterprise(passenger.getEnterprise_id());
                map.put("overdraw", enterprise.isAllowOverdraw());
                map.put(
                    "virtual",
                    enterprise.getDrawMoney().add(enterprise.getNodrawMoney())
                        .setScale(2, BigDecimal.ROUND_HALF_UP));
            }

            // 优惠券
            if (null != order.getCouponId()) {
                Coupon coupon = couponService.findOne(order.getCouponId());
                if (null != coupon) {
                    CouponRule couponRule = coupon.getCouponRule();
                    if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                        map.put("couponMoney", couponRule.getMoney());
                    } else if (couponRule.getType().equals(CouponRule.TYPE_DISCOUNT)) {
                        map.put("discount", couponRule.getDiscount());
                    }
                    map.put("coupon_type", CouponRule.TYPE_DISCOUNT);
                }
            }

            map.put("employId", driver.getId());
            map.put("employName", driver.getName());
            map.put("employPhone", driver.getPhone());

            map.put("success", true);
            return map;

        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "内部服务器错误");
            return map;
        }
    }

    @RequestMapping(value = "checkTask", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> checkTask(Long orderId) {

        Map<String, Object> map = new HashMap<String, Object>();
        Order order = freightService.findOne(orderId);
        if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
            map.put("finished", true);
            map.put("message", "请求成功");
        } else {
            map.put("finished", false);
            map.put("message", "请求成功");
        }

        map.put("success", true);
        return map;

    }

    @RequestMapping(value = "confirmTask", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> confirmTask(Long orderId, BigDecimal realCash,
        BigDecimal guoluMoney, BigDecimal yuanchengMoney, BigDecimal otherMoney, Double mileage,
        Integer waitedTime, Integer travelTime,
        @RequestParam(required = false, value = "startPrice") BigDecimal startPrice,
        @RequestParam(required = false, value = "mileagePrice") BigDecimal mileagePrice,
        @RequestParam(required = false, value = "runTimePrice") BigDecimal runTimePrice,
        @RequestParam(required = false, value = "waitPrice") BigDecimal waitPrice,
        @RequestParam(required = false, value = "memo") String memo,
        @RequestParam(required = false, value = "xml") String xml) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {

            logger
                .error(
                    "recv orderId:{},realCash:{},guoluMoney:{},yuanchengMoney:{},otherMoney:{},"
                        + "mileage:{},waitedTime:{},travelTime:{},startPrice:{},mileagePrice:{},runTimePrice:{},waitPrice:{},xml:{}",
                    orderId, realCash, guoluMoney, yuanchengMoney, otherMoney, mileage, waitedTime,
                    travelTime, startPrice, mileagePrice, runTimePrice, waitPrice, xml);

            if (null == orderId || null == realCash || null == mileage || null == waitedTime
                || null == travelTime) {
                map.put("success", false);
                map.put("message", "参数错误");
                return map;
            }
            Order order = freightService.findOne(orderId);
            if (null == order) {
                map.put("success", false);
                map.put("message", "订单不存在");
                return map;
            }

            if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                map.put("success", false);
                map.put("message", "订单状态不正确");
                return map;
            }

            if (order.getTreatment()) {
                map.put("success", true);
                map.put("message", "成功");
                map.put("type", "waitfinish");
                return map;
            }

            order.setGuoluMoney(guoluMoney);
            order.setYuanchengMoney(yuanchengMoney);
            order.setOtherMoney(otherMoney);
            order.setRealPay(realCash.doubleValue());

            // 优惠券
            Coupon coupon = null;
            BigDecimal coupon_hasPayed = BigDecimal.ZERO;
            Double discount = null;
            if (null != order.getCouponId()) {
                coupon = couponService.findOne(order.getCouponId());
                if (null != coupon) {
                    if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
                        coupon_hasPayed = coupon.getCouponRule().getMoney();
                    } else if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DISCOUNT)) {
                        discount = coupon.getCouponRule().getDiscount();
                        coupon_hasPayed = (realCash.subtract(order.getGuoluMoney())
                            .multiply(new BigDecimal(
                                1 - (discount / 10)))).setScale(0, BigDecimal.ROUND_DOWN);
                    }
                }
            }

            order.setCouponMoney(coupon_hasPayed);
            if (coupon_hasPayed.doubleValue() > 0 && null == order.getPrePayTypeDetail()) {
                order.setPrePayTypeDetail(PayTypeDetails.coupon);
            }
            order.setDiscount(discount);
            order.setMemo(memo);
            BigDecimal m = new BigDecimal(mileage);
            double df = m.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            order.setMileage(df);
            order.setWaitTime(waitedTime);
            order.setRunTime(travelTime);

            if (null != startPrice) {
                order.setStartPrice(startPrice.doubleValue());
            }
            if (null != mileagePrice) {
                order.setMileagePrice(mileagePrice.doubleValue());
            }
            if (null != runTimePrice) {
                order.setRunTimePrice(runTimePrice.doubleValue());
            }
            if (null != waitPrice) {
                order.setWaitCost(waitPrice.doubleValue());
            }

            order.setTreatment(true);
            Result<Order> result = freightService.confirmTask(order, xml);
            Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
            passenger.setPlateNumber(memo);
            passenger.setMileage(passenger.getMileage() + order.getMileage());// 累计公里数
            memberService.updatePassenger(passenger);

            if (result.isSuccess()) {

                BigDecimal money = new BigDecimal(order.getRealPay());// 还需支付的钱
                money = money.subtract(order.getGuoluMoney());
                money = money.subtract(coupon_hasPayed);
                if (money.doubleValue() < 0) {
                    money = BigDecimal.ZERO;
                }
                money = money.add(order.getGuoluMoney());

                // driverService.updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null,
                // order.getEmployId());
                if (money.doubleValue() <= 0) {
                    // 直接结算
                    Driver driver = driverService.findOne(order.getEmployId());
                    result = freightService
                        .completeTaskNewV3(order, passenger, driver, "clickComplete", null);

                    if (result.isSuccess()) {
                        map.put("success", true);
                        map.put("message", "成功");
                        map.put("type", "hasfinished");
                        return map;
                    } else {
                        map.put("success", false);
                        map.put("message", result.getMessage());
                        return map;
                    }
                } else {
                    // 进入确认页面
                    // 客户端提醒付费推送

                    FreightOrderConfirmEvent freightOrderConfirmEvent = new FreightOrderConfirmEvent(
                        order);
                    applicationEventMulticaster.multicastEvent(freightOrderConfirmEvent);

                    map.put("success", true);
                    map.put("message", "成功");
                    map.put("type", "waitfinish");
                    return map;
                }
            } else {
                map.put("success", false);
                map.put("message", result.getMessage());
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "内部服务器错误");
            return map;
        }
    }

    @RequestMapping(value = "finishTask", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> finishTask(Long orderId, String payType, String who) {

        logger.error("recv orderId:{},payType{}", orderId, payType);

        Map<String, Object> map = new HashMap<String, Object>();

        if (null == orderId || StringUtils.isBlank(payType)) {
            map.put("success", false);
            map.put("message", "参数错误");
            return map;
        }

        if (!"helppay".equals(payType) && !"sign".equals(payType) && !"balance".equals(payType)) {
            map.put("success", false);
            map.put("message", "支付方式应为代付、签单、余额中的一种");
            return map;
        }

        Order order = freightService.findOne(orderId);

        if (null == order) {
            map.put("success", false);
            map.put("message", "订单不存在");
            return map;
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
            map.put("success", false);
            map.put("message", "订单状态不正确");
            return map;
        }

        if (!order.getTreatment()) {
            map.put("success", false);
            map.put("message", "还未确认订单，不能结算");
            return map;
        }

        Driver driver = driverService.findOne(order.getEmployId());
        if ("helppay".equals(payType)) {// 如果是代付，服务人员收到现金，余额减钱
            if (null == driver) {
                map.put("success", false);
                map.put("message", "订单服务人员不存在，无法代付");
                return map;
            }
        }

        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        if (null != passenger) {
            if ("sign".equals(payType)) {// 签单支付
                if (!passenger.isAllowOverdraw()) {
                    map.put("success", false);
                    map.put("message", "当前客户不能签单");
                    return map;
                }
            } else if ("balance".equals(payType)) {// 余额支付

                Double afterPayMoney = 0d;
                if (null != order.getPrePayTypeDetail()) {
                    if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                        afterPayMoney = order.getRealPay() - order.getCouponMoney().doubleValue();
                    }
                } else {
                    afterPayMoney = order.getRealPay();
                }

                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    BigDecimal shengyuMoney = BigDecimal.ZERO;
                    shengyuMoney = shengyuMoney.add(passenger.getNodrawMoney());
                    if (passenger.getDrawMoney().doubleValue() > 0) {
                        shengyuMoney = shengyuMoney.add(passenger.getDrawMoney());
                    }
                    if (shengyuMoney.doubleValue() < afterPayMoney) {
                        map.put("success", false);
                        map.put("message", "余额不足");
                        return map;
                    }
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = memberService
                        .findOneEnterprise(passenger.getEnterprise_id());
                    BigDecimal shengyuMoney = BigDecimal.ZERO;
                    shengyuMoney = shengyuMoney.add(enterprise.getNodrawMoney());
                    if (enterprise.getDrawMoney().doubleValue() > 0) {
                        shengyuMoney = shengyuMoney.add(enterprise.getDrawMoney());
                    }
                    if (shengyuMoney.doubleValue() < afterPayMoney) {
                        map.put("success", false);
                        map.put("message", "余额不足");
                        return map;
                    }
                }
            }
        }

        try {

            Result<Order> result = freightService
                .completeTaskNewV3(order, passenger, driver, "clickPay",
                    payType);

            if (result.isSuccess()) {

                if (StringUtils.isNotBlank(who) && who.equals("passenger")) {
                    OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(
                        driver, order.getId(), "freight");
                    applicationEventMulticaster.multicastEvent(orderPassengerHasPayEvent);
                }

                map.put("success", true);
                return map;
            } else {
                map.put("success", false);
                map.put("message", result.getMessage());
                return map;
            }

        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "内部服务器错误");
            return map;
        }

    }

    @RequestMapping(value = "clientPayData", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> clientPayData(Long orderId) {

        Map<String, Object> map = new HashMap<String, Object>();

        Setting setting = settingUtils.get();

        Order order = freightService.findOne(orderId);

        BigDecimal coupon_hasPayed = order.getCouponMoney();

        map.put("couponMoney", coupon_hasPayed);

        map.put("realCash", new BigDecimal(order.getRealPay()).subtract(order.getGuoluMoney()));
        map.put("guoluMoney", order.getGuoluMoney());
        map.put("yuanchengMoney", order.getYuanchengMoney());
        map.put("otherMoney", order.getOtherMoney());

        if (null != order.getPrePayTypeDetail()) {
            if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                map.put("preyMoney", BigDecimal.ZERO);
            }
        } else {
            map.put("preyMoney", BigDecimal.ZERO);
        }

        if (null != order.getPrePayTypeDetail()) {
            if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                BigDecimal payMoney = new BigDecimal(order.getRealPay());// 还需支付的钱
                payMoney = payMoney.subtract(order.getGuoluMoney());
                payMoney = payMoney.subtract(coupon_hasPayed);
                if (payMoney.doubleValue() < 0) {
                    payMoney = BigDecimal.ZERO;
                }
                payMoney = payMoney.add(order.getGuoluMoney());

                map.put("payMoney", payMoney);
            }
        } else {
            map.put("payMoney", new BigDecimal(order.getRealPay()));
        }

        Boolean aliPay = true;
        Boolean weixinPay = true;

        if (StringUtils.isBlank(setting.getAlipayPartnerID())
            || StringUtils.isBlank(setting.getAlipaySellerID())
            || StringUtils.isBlank(setting.getAlipayPartnerPrivKey())) {
            aliPay = false;
        }
        if (StringUtils.isBlank(setting.getWxAppID()) || StringUtils
            .isBlank(setting.getWxAppSecret())
            || StringUtils.isBlank(setting.getWxPartnerID())
            || StringUtils.isBlank(setting.getWxPartnerKey())) {
            weixinPay = false;
        }
        Boolean unionPay = true;
        if (StringUtils.isBlank(setting.getMerId()) || StringUtils.isBlank(setting.getAcpProdEnc())
            || StringUtils.isBlank(setting.getAcpProdMiddle())
            || StringUtils.isBlank(setting.getAcpProdRoot())
            || StringUtils.isBlank(setting.getAcpsdkSignCertPath())
            || StringUtils.isBlank(setting.getAcpsdkSignCertPwd())) {
            unionPay = false;
        }
        Boolean bestPay = true;
        if (StringUtils.isBlank(setting.getMerchantId()) || StringUtils.isBlank(setting.getMerKey())
            || StringUtils.isBlank(setting.getRiskcontrolinfo())
            || StringUtils.isBlank(setting.getMchPwd())) {
            bestPay = false;
        }
        map.put("unionPay", unionPay);
        map.put("weixinPay", weixinPay);
        map.put("aliPay", aliPay);
        map.put("bestPay", bestPay);
        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        if (passenger.getType() == Passenger.TYPE_PASSENGER) {
            map.put("overdraw", passenger.isAllowOverdraw());
        } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
            Enterprise enterprise = memberService.findOneEnterprise(passenger.getEnterprise_id());
            map.put("overdraw", enterprise.isAllowOverdraw());
        }

        map.put("success", true);
        return map;
    }

    // 客户端APP后支付
    @RequestMapping(value = "alipay/afterpay")
    public @ResponseBody
    Map<String, Object> alipayAfterpay(HttpServletResponse response,
        HttpServletRequest request, Long orderId) {
        Map<String, Object> mapData = new HashMap<String, Object>();
        try {
            Order order = freightService.findOne(orderId);

            if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                mapData.put("success", false);
                mapData.put("message", ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode());
                return mapData;
            }

            if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                mapData.put("success", false);
                mapData.put("message", ErrorConstantV4.ORDER_STATUS_ERROR.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_STATUS_ERROR.getCode());
                return mapData;
            }

            if (!order.getTreatment()) {
                mapData.put("success", false);
                mapData.put("message", ErrorConstantV4.ORDER_NOT_CONFIRM.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_NOT_CONFIRM.getCode());
                return mapData;
            }

            BigDecimal money = BigDecimal.ZERO;
            if (null != order.getPrePayTypeDetail()) {
                if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    money = new BigDecimal(order.getRealPay()).subtract(order.getCouponMoney());
                }
            } else {
                money = new BigDecimal(order.getRealPay());
            }
            money = money.setScale(2, BigDecimal.ROUND_HALF_UP);

            PayRecordOrder payRecordOrder = new PayRecordOrder();
            payRecordOrder.setMoney(money);
            payRecordOrder.setOrderId(orderId);
            payRecordOrder.setPayRecordTypeOrder(PayRecordTypeOrder.alipay);
            payRecordOrder.setTreatment(false);
            Result<PayRecordOrder> result = freightService.createPayRecordOrder(payRecordOrder);

            Setting setting = settingUtils.get();

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("PartnerID", setting.getAlipayPartnerID());
            map.put("SellerID", setting.getAlipaySellerID());
            map.put("PartnerPrivKey", setting.getAlipayPartnerPrivKey());
            map.put("PartnerPublicKey", AlipayConfig.ali_public_key);
            map.put("tradeNO", "hy_af_" + result.getResult().getId() + "_" + order.getId());
            map.put("productName", "货运结算付费");
            map.put("productDescription", "货运结算付费");
            map.put("amount", money);
            map.put("notifyURL", setting.getWebUrl() + "/api/freight/alipay/afternotify");
            String content = MemberOrderSign.sign(map);
            String sign = RSA.sign(content, setting.getAlipayPartnerPrivKey(), "utf-8");
            sign = URLEncoder.encode(sign, "utf-8");
            String url = content + "&sign=\"" + sign + "\"&sign_type=\"RSA\"";
            mapData.put("success", true);
            mapData.put("url", url);
        } catch (Exception e) {
            mapData.put("success", false);
            mapData.put("message", "支付接口请求失败");
        }
        return mapData;
    }

    // 支付宝支付后的接口
    @RequestMapping(value = "alipay/afternotify")
    public synchronized @ResponseBody
    String alipayAfterNotify(HttpServletResponse response,
        HttpServletRequest request) throws UnsupportedEncodingException {
        Setting setting = settingUtils.get();
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr =
                    (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        // 商户订单号
        String out_trade_no = new String(
            request.getParameter("out_trade_no").getBytes("ISO-8859-1"),
            "UTF-8");
        // 支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),
            "UTF-8");
        // 交易状态
        String trade_status = new String(
            request.getParameter("trade_status").getBytes("ISO-8859-1"),
            "UTF-8");
        // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        logger.error("商户订单号：" + out_trade_no);
        logger.error("交易号：" + trade_no + "交易状态：" + trade_status);
        if (AlipayNotify.verify(params, setting)) {// 验证成功
            if (trade_status.equals("TRADE_FINISHED")) {
                // 调用货运系统支付成功
                Long orderId = Long.valueOf(out_trade_no.split("_")[2]);
                PayRecordOrder payRecordOrder = freightService.findOnePayRecordOrder(orderId);
                if (payRecordOrder.isTreatment()) {
                    return "success";
                }

                Order order = freightService.findOne(payRecordOrder.getOrderId());

                if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                    return "success";
                }

                Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
                Driver driver = driverService.findOne(order.getEmployId());

                Result<Order> result = freightService.completeTaskNewV3(order, passenger, driver,
                    "onlinePay", "alipay");

                if (result.isSuccess()) {

                    Result<PayRecordOrder> result2 = freightService
                        .payRecordOrderTreatment(payRecordOrder);

                    if (result2.isSuccess()) {

                        OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(
                            driver, order.getId(), "freight");
                        applicationEventMulticaster.multicastEvent(orderPassengerHasPayEvent);

                        return "success";
                    } else {
                        return "fail";
                    }

                } else {
                    return "fail";
                }

            } else if (trade_status.equals("TRADE_SUCCESS")) {
                // 调用货运系统支付成功,把临时表的订单信息新增到真实表中
                Long orderId = Long.valueOf(out_trade_no.split("_")[2]);
                PayRecordOrder payRecordOrder = freightService.findOnePayRecordOrder(orderId);
                if (payRecordOrder.isTreatment()) {
                    return "success";
                }

                Order order = freightService.findOne(payRecordOrder.getOrderId());

                if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                    return "success";
                }

                Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
                Driver driver = driverService.findOne(order.getEmployId());

                Result<Order> result = freightService.completeTaskNewV3(order, passenger, driver,
                    "onlinePay", "alipay");

                if (result.isSuccess()) {

                    Result<PayRecordOrder> result2 = freightService
                        .payRecordOrderTreatment(payRecordOrder);

                    if (result2.isSuccess()) {

                        OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(
                            driver, order.getId(), "freight");
                        applicationEventMulticaster.multicastEvent(orderPassengerHasPayEvent);

                        return "success";
                    } else {
                        return "fail";
                    }

                } else {
                    return "fail";
                }

            }

            return "fail";
        } else {
            return "fail";
        }

    }

    // 客户端APP后支付
    @RequestMapping(value = "unionpay/afterpay")
    public @ResponseBody
    Map<String, Object> unionpayAfterpay(HttpServletResponse response,
        HttpServletRequest request, Long orderId) {
        Map<String, Object> mapData = new HashMap<String, Object>();
        try {
            Order order = freightService.findOne(orderId);

            if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                mapData.put("message", ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode());
                return mapData;
            }

            if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                mapData.put("message", ErrorConstantV4.ORDER_STATUS_ERROR.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_STATUS_ERROR.getCode());
                return mapData;
            }

            if (!order.getTreatment()) {
                mapData.put("message", ErrorConstantV4.ORDER_NOT_CONFIRM.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_NOT_CONFIRM.getCode());
                return mapData;
            }

            BigDecimal money = BigDecimal.ZERO;
            if (null != order.getPrePayTypeDetail()) {
                if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    money = new BigDecimal(order.getRealPay()).subtract(order.getCouponMoney());
                }
            } else {
                money = new BigDecimal(order.getRealPay());
            }
            money = money.setScale(2, BigDecimal.ROUND_HALF_UP);

            PayRecordOrder payRecordOrder = new PayRecordOrder();
            payRecordOrder.setMoney(money);
            payRecordOrder.setOrderId(orderId);
            payRecordOrder.setPayRecordTypeOrder(PayRecordTypeOrder.unionpay);
            payRecordOrder.setTreatment(false);
            Result<PayRecordOrder> result = freightService.createPayRecordOrder(payRecordOrder);

            Setting setting = settingUtils.get();

            // 从classpath加载acp_sdk.properties文件
            SDKConfig.getConfig().loadPropertiesFromSrc(setting);

            String payOrderId = DemoBase.getOrderId();
            int paymoney = money.multiply(new BigDecimal(100))
                .intValue(); // txnAmt以'元'为单位,乘以100以'分'为单位传给银联
            String txnTime = DemoBase.getCurrentTime(); // 交易时间
            String merId = setting.getMerId(); // 获取商户号
            Map<String, String> contentData = new HashMap<String, String>();

            /*** 银联全渠道系统，产品参数，除了encoding自行选择外其他不需修改 ***/
            contentData.put("version", "5.1.0"); // 版本号 全渠道默认值
            contentData.put("encoding", "UTF-8"); // 字符集编码 可以使用UTF-8,GBK两种方式
            contentData.put("signMethod", "01"); // 签名方法
            contentData.put("txnType", "01"); // 交易类型 01:消费
            contentData.put("txnSubType", "01"); // 交易子类 01：消费
            contentData.put("bizType", "000201"); // 填写000201
            contentData.put("channelType", "08"); // 渠道类型 08手机

            /*** 商户接入参数 ***/
            contentData.put("merId", merId); // 商户号码，请改成自己申请的商户号或者open上注册得来的777商户号测试
            contentData.put("accessType", "0"); // 接入类型，商户接入填0 ，不需修改（0：直连商户， 1： 收单机构
            // 2：平台商户）
            contentData.put("orderId", payOrderId); // 商户订单号，8-40位数字字母，不能含“-”或“_”，可以自行定制规则
            contentData
                .put("txnTime", txnTime); // 订单发送时间，取系统时间，格式为YYYYMMDDhhmmss，必须取当前时间，否则会报txnTime无效
            contentData.put("accType", "01"); // 账号类型 01：银行卡02：存折03：IC卡帐号类型(卡介质)
            contentData.put("txnAmt", String.valueOf(paymoney)); // 交易金额 单位为分，不能带小数点
            contentData.put("currencyCode", "156"); // 境内商户固定 156 人民币
            String out_trade_no = "hy_af_" + result.getResult().getId() + "_" + order.getId();
            contentData.put("reqReserved", out_trade_no);
            String backUrl = "";
            if (setting.getWebUrl().endsWith("/")) {
                backUrl = setting.getWebUrl() + "api/freight/unionpay/afternotify";
            } else {
                backUrl = setting.getWebUrl() + "/" + "api/freight/unionpay/afternotify";
            }
            contentData.put("backUrl", backUrl);

            Map<String, String> reqData = AcpService.sign(contentData,
                DemoBase.encoding); // 报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
            String requestAppUrl = SDKConfig.getConfig()
                .getAppRequestUrl(); // 交易请求url从配置文件读取对应属性文件acp_sdk.properties中的
            // acpsdk.backTransUrl
            Map<String, String> rspData = AcpService.post(reqData, requestAppUrl,
                DemoBase.encoding); // 发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

            if (!rspData.isEmpty()) {
                if (AcpService.validate(rspData, DemoBase.encoding)) {
                    LogUtil.writeLog("验证签名成功");
                    String respCode = rspData.get("respCode");
                    if (("00").equals(respCode)) {
                        String tn = rspData.get("tn");
                        mapData.put("message", "成功");
                        mapData.put("code", 0);
                        mapData.put("data", tn);
                        return mapData;
                    } else {
                        mapData.put("success", false);
                        mapData.put("message", "验证签名失败");
                        mapData.put("code", -1);
                        return mapData;
                    }
                } else {
                    mapData.put("success", false);
                    mapData.put("message", "验证签名失败");
                    mapData.put("code", -1);
                    return mapData;
                }
            } else {
                mapData.put("success", false);
                mapData.put("message", "验证签名失败");
                mapData.put("code", -1);
                return mapData;
            }
        } catch (Exception e) {
            mapData.put("success", false);
            mapData.put("message", "支付接口请求失败");
        }
        return mapData;
    }

    // 银联支付后的接口
    @RequestMapping(value = "unionpay/afternotify")
    public synchronized @ResponseBody
    void unionpayAfterNotify(HttpServletResponse resp,
        HttpServletRequest req) throws IOException {
        LogUtil.writeLog("BackRcvResponse接收后台通知开始");

        String encoding = req.getParameter(SDKConstants.param_encoding);
        // 获取银联通知服务器发送的后台通知参数
        Map<String, String> reqParam = getAllRequestParam(req);

        LogUtil.printRequestLog(reqParam);

        Map<String, String> valideData = null;
        if (null != reqParam && !reqParam.isEmpty()) {
            Iterator<Entry<String, String>> it = reqParam.entrySet().iterator();
            valideData = new HashMap<String, String>(reqParam.size());
            while (it.hasNext()) {
                Entry<String, String> e = it.next();
                String key = (String) e.getKey();
                String value = (String) e.getValue();
                valideData.put(key, value);
            }
        }

        // 重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
        if (!AcpService.validate(valideData, encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            // 验签失败，需解决验签问题
        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            LogUtil.writeLog("后台通知货运的数据orderId:" + valideData.get("orderId"));
            String respCode = valideData.get("respCode");
            if ("00".equals(respCode)) {
                String out_trade_no = valideData.get("reqReserved"); // 获取后台通知的数据，其他字段也可用类似方式获取
                // 验证成功
                Long orderId = Long.valueOf(out_trade_no.split("_")[2]);

                PayRecordOrder payRecordOrder = freightService.findOnePayRecordOrder(orderId);
                if (!payRecordOrder.isTreatment()) {
                    Order order = freightService.findOne(payRecordOrder.getOrderId());
                    if (!order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                        Passenger passenger = memberService
                            .findOnePassenger(order.getPassengerId());
                        Driver driver = driverService.findOne(order.getEmployId());

                        Result<Order> result = freightService
                            .completeTaskNewV3(order, passenger, driver,
                                "onlinePay", "unionpay");

                        if (result.isSuccess()) {
                            Result<PayRecordOrder> result2 = freightService
                                .payRecordOrderTreatment(payRecordOrder);
                            if (result2.isSuccess()) {
                                OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(
                                    driver, order.getId(), "freight");
                                applicationEventMulticaster
                                    .multicastEvent(orderPassengerHasPayEvent);
                                // 返回给银联服务器http 200 状态码
                                resp.getWriter().print("ok");
                            }
                        }
                    }
                }
            }
        }
        LogUtil.writeLog("BackRcvResponse接收后台通知结束");
    }

    // 微信支付前接口
    @RequestMapping(value = "wx/afterpay")
    public synchronized @ResponseBody
    SortedMap<String, String> wxAfterpay(
        HttpServletResponse response, HttpServletRequest request, Long orderId) {

        Order order = freightService.findOne(orderId);

        SortedMap<String, String> finalpackage = new TreeMap<String, String>();

        if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
            finalpackage.put("success", String.valueOf(false));
            finalpackage.put("message", ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
            finalpackage
                .put("code", String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()));
            return finalpackage;
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
            finalpackage.put("success", String.valueOf(false));
            finalpackage.put("message", ErrorConstantV4.ORDER_STATUS_ERROR.getMessage());
            finalpackage.put("code", String.valueOf(ErrorConstantV4.ORDER_STATUS_ERROR.getCode()));
            return finalpackage;
        }

        if (!order.getTreatment()) {
            finalpackage.put("success", String.valueOf(false));
            finalpackage.put("message", ErrorConstantV4.ORDER_NOT_CONFIRM.getMessage());
            finalpackage.put("code", String.valueOf(ErrorConstantV4.ORDER_NOT_CONFIRM.getCode()));
            return finalpackage;
        }

        BigDecimal money = BigDecimal.ZERO;
        if (null != order.getPrePayTypeDetail()) {
            if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                money = new BigDecimal(order.getRealPay()).subtract(order.getCouponMoney());
            }
        } else {
            money = new BigDecimal(order.getRealPay());
        }
        money = money.setScale(2, BigDecimal.ROUND_HALF_UP);

        PayRecordOrder payRecordOrder = new PayRecordOrder();
        payRecordOrder.setMoney(money);
        payRecordOrder.setOrderId(orderId);
        payRecordOrder.setPayRecordTypeOrder(PayRecordTypeOrder.weixin);
        payRecordOrder.setTreatment(false);
        Result<PayRecordOrder> result = freightService.createPayRecordOrder(payRecordOrder);

        Setting setting = settingUtils.get();
        String createOrderURL = Configuration.createOrderURL;

        // 商户相关资料
        String appid = setting.getWxAppID();
        String appsecret = setting.getWxAppSecret();
        String partner = setting.getWxPartnerID();
        String partnerkey = setting.getWxPartnerKey();

        String currTime = TenpayUtil.getCurrTime();
        // 8位日期
        String strTime = currTime.substring(8, currTime.length());
        // 四位随机数
        String strRandom = TenpayUtil.buildRandom(6) + "";
        // 10位序列号,可以自行调整。
        String strReq = strTime + strRandom;
        // 商户号
        String mch_id = partner;
        // 随机数
        String nonce_str = strReq;
        // 商品描述
        String body = "货运结算付费-" + order.getOrderNo();
        // 商户订单号
        String out_trade_no = "hy_af_" + result.getResult().getId() + "_" + order.getId();
        // 总金额以分为单位，不带小数点
        String total_fee = String.valueOf(money.multiply(new BigDecimal(100)).intValue());
        // 订单生成的机器 IP
        String spbill_create_ip = request.getRemoteAddr();

        // 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        String notify_url = setting.getWebUrl() + "/api/freight/wx/afternotify";

        String trade_type = "APP";

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appid);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", out_trade_no);

        // 这里写的金额为1 分到时修改
        // packageParams.put("total_fee", "1");
        packageParams.put("total_fee", total_fee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", notify_url);
        packageParams.put("trade_type", trade_type);

        RequestHandler reqHandler = new RequestHandler(request, response);
        reqHandler.init(appid, appsecret, partnerkey);

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<mch_id>" + mch_id + "</mch_id>"
            + "<nonce_str>" + nonce_str + "</nonce_str>" + "<sign>" + sign + "</sign>"
            + "<body><![CDATA[" + body + "]]></body>" + "<out_trade_no>"
            + out_trade_no
            + "</out_trade_no>"
            +
            // "<total_fee>"+1+"</total_fee>"+
            "<total_fee>" + total_fee + "</total_fee>" + "<spbill_create_ip>" + spbill_create_ip
            + "</spbill_create_ip>" + "<notify_url>" + notify_url + "</notify_url>" + "<trade_type>"
            + trade_type + "</trade_type>" + "</xml>";

        String prepay_id = "";
        try {
            prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);
            if (prepay_id.equals("")) {
                logger.error("统一支付接口获取预支付订单出错");
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("appid", appid);
        finalpackage.put("partnerid", partner);
        finalpackage.put("prepayid", prepay_id);
        finalpackage.put("package", "Sign=WXPay");
        finalpackage.put("noncestr", nonce_str);
        finalpackage.put("timestamp", timestamp);
        String finalsign = reqHandler.createSign(finalpackage);
        finalpackage.put("sign", finalsign);

        finalpackage.put("success", Boolean.TRUE.toString());

        return finalpackage;

    }

    // 微信支付后接口
    @RequestMapping("wx/afternotify")
    public synchronized @ResponseBody
    String wxAfterNotify(HttpServletResponse response,
        HttpServletRequest request) throws Exception {

        String out_trade_no = "";

        try {

            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String strxml = sb.toString();

            InputStream in = new ByteArrayInputStream(strxml.getBytes());
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(in);
            Element root = doc.getRootElement();
            List list = root.getChildren();
            Iterator it = list.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String k = e.getName();
                if (k.equals("out_trade_no")) {
                    out_trade_no = e.getText();
                }
            }

            try {
                // 关闭流
                if (null != in) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (StringUtils.isBlank(out_trade_no)) {
                return "FAIL";
            }

            Long orderId = Long.valueOf(out_trade_no.split("_")[2]);

            PayRecordOrder payRecordOrder = freightService.findOnePayRecordOrder(orderId);
            if (payRecordOrder.isTreatment()) {
                return "SUCCESS";
            }

            Order order = freightService.findOne(payRecordOrder.getOrderId());

            if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                return "SUCCESS";
            }

            Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
            Driver driver = driverService.findOne(order.getEmployId());

            Result<Order> result = freightService.completeTaskNewV3(order, passenger, driver,
                "onlinePay", "weixin");

            if (result.isSuccess()) {

                Result<PayRecordOrder> result2 = freightService
                    .payRecordOrderTreatment(payRecordOrder);

                if (result2.isSuccess()) {

                    OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(
                        driver, order.getId(), "freight");
                    applicationEventMulticaster.multicastEvent(orderPassengerHasPayEvent);

                    return "SUCCESS";
                } else {
                    return "FAIL";
                }

            } else {
                return "FAIL";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "FAIL";
        }

    }

    /***************************************************************************************************************************************
     *
     * 微信货运微信支付
     *
     ***************************************************************************************************************************************/

    /**
     * 微信货运微信支付
     *
     * @param response
     * @param request
     * @param orderId  订单号
     * @param openId   微信OPENID
     * @return
     */
    @RequestMapping(value = "wx/prepayId_jsapi")
    public synchronized @ResponseBody
    SortedMap<String, String> prepayIdJsapi(
        HttpServletResponse response, HttpServletRequest request, Long orderId, String openId) {
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();

        if (null == orderId || null == openId) {
            finalpackage.put("success", String.valueOf(false));
            finalpackage.put("message", ErrorConstantV4.PARAM_ERROR.getMessage());
            finalpackage.put("code", String.valueOf(ErrorConstantV4.PARAM_ERROR.getCode()));
            return finalpackage;
        }

        Order order = freightService.findOne(orderId);

        if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
            finalpackage.put("success", String.valueOf(false));
            finalpackage.put("message", ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
            finalpackage
                .put("code", String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()));
            return finalpackage;
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
            finalpackage.put("success", String.valueOf(false));
            finalpackage.put("message", ErrorConstantV4.ORDER_STATUS_ERROR.getMessage());
            finalpackage.put("code", String.valueOf(ErrorConstantV4.ORDER_STATUS_ERROR.getCode()));
            return finalpackage;
        }

        if (!order.getTreatment()) {
            finalpackage.put("success", String.valueOf(false));
            finalpackage.put("message", ErrorConstantV4.ORDER_NOT_CONFIRM.getMessage());
            finalpackage.put("code", String.valueOf(ErrorConstantV4.ORDER_NOT_CONFIRM.getCode()));
            return finalpackage;
        }

        BigDecimal money = BigDecimal.ZERO;
        if (null != order.getPrePayTypeDetail()) {
            if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                money = new BigDecimal(order.getRealPay()).subtract(order.getCouponMoney());
            }
        } else {
            money = new BigDecimal(order.getRealPay());
        }
        money = money.setScale(2, BigDecimal.ROUND_HALF_UP);

        PayRecordOrder payRecordOrder = new PayRecordOrder();
        payRecordOrder.setMoney(money);
        payRecordOrder.setOrderId(orderId);
        payRecordOrder.setPayRecordTypeOrder(PayRecordTypeOrder.weixin);
        payRecordOrder.setTreatment(false);
        Result<PayRecordOrder> result = freightService.createPayRecordOrder(payRecordOrder);

        WxSetting wxSetting = settingUtils.getWx();
        String createOrderURL = Configuration.createOrderURL;

        // 商户相关资料
        String appid = wxSetting.getWxAppId();
        String appsecret = wxSetting.getWxAppSecret();
        String partner = wxSetting.getWxPartnerId();
        String partnerkey = wxSetting.getWxPartnerKey();

        String currTime = TenpayUtil.getCurrTime();
        // 8位日期
        String strTime = currTime.substring(8, currTime.length());
        // 四位随机数
        String strRandom = TenpayUtil.buildRandom(6) + "";
        // 10位序列号,可以自行调整。
        String strReq = strTime + strRandom;
        // 商户号
        String mch_id = partner;
        // 随机数
        String nonce_str = strReq;
        // 商品描述
        String body = "货运结算付费-" + order.getOrderNo();
        // 商户订单号
        String out_trade_no = "hy_af_" + result.getResult().getId() + "_" + order.getId();
        // 总金额以分为单位，不带小数点
        String total_fee = String.valueOf(money.multiply(new BigDecimal(100)).intValue());
        // 订单生成的机器 IP
        String spbill_create_ip = request.getRemoteAddr();

        // 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        Setting setting = settingUtils.get();
        String notify_url = setting.getWebUrl() + "/api/freight/wx/afternotify";

        String trade_type = "JSAPI";

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appid);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("total_fee", total_fee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", notify_url);
        packageParams.put("trade_type", trade_type);
        packageParams.put("openid", openId);

        RequestHandler reqHandler = new RequestHandler(request, response);
        reqHandler.init(appid, appsecret, partnerkey);

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<mch_id>" + mch_id + "</mch_id>"
            + "<nonce_str>" + nonce_str + "</nonce_str>" + "<sign>" + sign + "</sign>"
            + "<body><![CDATA[" + body + "]]></body>" + "<out_trade_no>" + out_trade_no
            + "</out_trade_no>" + "<total_fee>" + total_fee + "</total_fee>" + "<spbill_create_ip>"
            + spbill_create_ip + "</spbill_create_ip>" + "<notify_url>" + notify_url
            + "</notify_url>"
            + "<trade_type>" + trade_type + "</trade_type>" + "<openid>" + openId + "</openid>"
            + "</xml>";

        String prepay_id = "";
        try {
            prepay_id = GetWxOrderno.getPayNo(createOrderURL, xml);
            if (prepay_id.equals("")) {
                logger.error("统一支付接口获取预支付订单出错");
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("appId", appid);
        finalpackage.put("timeStamp", timestamp);
        finalpackage.put("nonceStr", nonce_str);
        finalpackage.put("package", "prepay_id=" + prepay_id);
        finalpackage.put("signType", "MD5");
        String finalsign = reqHandler.createSign(finalpackage);
        finalpackage.put("paySign", finalsign);

        return finalpackage;

    }

    // 翼支付 支付前接口
    @RequestMapping(value = "bestpay/afterpay")
    public @ResponseBody
    Map<String, Object> bestpayAfterpay(HttpServletResponse response,
        HttpServletRequest request, Long orderId) {
        Map<String, Object> mapData = new HashMap<String, Object>();
        try {
            Order order = freightService.findOne(orderId);

            if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                mapData.put("success", false);
                mapData.put("message", ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode());
                return mapData;
            }

            if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                mapData.put("success", false);
                mapData.put("message", ErrorConstantV4.ORDER_STATUS_ERROR.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_STATUS_ERROR.getCode());
                return mapData;
            }

            if (!order.getTreatment()) {
                mapData.put("success", false);
                mapData.put("message", ErrorConstantV4.ORDER_NOT_CONFIRM.getMessage());
                mapData.put("code", ErrorConstantV4.ORDER_NOT_CONFIRM.getCode());
                return mapData;
            }

            BigDecimal money = BigDecimal.ZERO;
            if (null != order.getPrePayTypeDetail()) {
                if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    money = new BigDecimal(order.getRealPay()).subtract(order.getCouponMoney());
                }
            } else {
                money = new BigDecimal(order.getRealPay());
            }
            money = money.setScale(2, BigDecimal.ROUND_HALF_UP);

            PayRecordOrder payRecordOrder = new PayRecordOrder();
            payRecordOrder.setMoney(money);
            payRecordOrder.setOrderId(orderId);
            payRecordOrder.setPayRecordTypeOrder(PayRecordTypeOrder.bestpay);
            payRecordOrder.setTreatment(false);
            Result<PayRecordOrder> result = freightService.createPayRecordOrder(payRecordOrder);

            // 获取系统设置
            Setting setting = settingUtils.get();
            String callBackUrl = setting.getWebUrl() + "/api/freight/bestpay/afternotify";
            String createUrl = "https://webpaywg.bestpay.com.cn/order.action";

            // 获取商户信息
            String mch_id = setting.getMerchantId();
            String mch_key = setting.getMerKey();
            String mch_pwd = setting.getMchPwd();
            String riskInfo = setting.getRiskcontrolinfo();
            String attach_order_id = "hy_af_" + result.getResult().getId() + "_" + order
                .getId(); // 商户订单号,这里作为附加信息，因为订单不能个包含特殊字符
            String body = "货运结算付费" + order.getOrderNo();

            // 使用随机数来作为订单流水号
            String currTime = TenpayUtil.getCurrTime();
            String strTime = currTime.substring(8, currTime.length()); // 8位日期
            String strRandom = TenpayUtil.buildRandom(6) + ""; // 四位随机数
            String strReq = strTime + strRandom; // 10位序列号,可以自行调整

            String phone = order.getPassengerPhone();
            // 格式化金额0.00
            DecimalFormat myformat = new java.text.DecimalFormat("0.00");
            String money_ = myformat.format(money);

            // 订单模型
            String total_fee = String
                .valueOf(money.multiply(new BigDecimal(100)).intValue()); // 元转分
            BestPayOrderModel orderModel = new BestPayOrderModel();
            orderModel.setATTACH(attach_order_id);
            orderModel.setCITYCODE("");
            orderModel.setDIVDETAILS("");
            orderModel.setENCODE("");
            orderModel.setENCODETYPE("1");
            orderModel.setKEY(mch_key);
            orderModel.setLOGINNO("");
            orderModel.setMERCHANTID(mch_id);
            orderModel.setORDERAMT(total_fee); // 分
            orderModel.setORDERCCY("RMB");
            orderModel.setORDERREQTIME(currTime);
            orderModel.setORDERREQTRANSEQ(strReq);
            orderModel.setORDERSEQ(strReq);
            orderModel.setPRODUCTDESC(body);
            orderModel.setPRODUCTID("04");
            orderModel.setPROVINCECODE("");
            orderModel.setRISKCONTROLINFO(riskInfo);
            orderModel.setSERVICECODE("05");
            orderModel.setSESSIONKEY("");
            orderModel.setSUBMERCHANTID("");
            orderModel.setTRANSCODE("01");
            boolean rs = BestPayCreateOrder.createByApp(createUrl, orderModel);

            // 下单失败
            if (!rs) {
                mapData.put("success", false);
                mapData.put("message", "翼支付app下单失败");
                return mapData;
            }

            // 签名参数
            StringBuffer md5Buffer = new StringBuffer();
            md5Buffer.append("SERVICE=").append("mobile.security.pay").append("&MERCHANTID=")
                .append(mch_id).append("&MERCHANTPWD=").append(mch_pwd).append("&SUBMERCHANTID=")
                .append("").append("&BACKMERCHANTURL=").append(callBackUrl).append("&ORDERSEQ=")
                .append(strReq).append("&ORDERREQTRANSEQ=").append(strReq).append("&ORDERTIME=")
                .append(currTime).append("&ORDERVALIDITYTIME=").append("").append("&CURTYPE=")
                .append("RMB").append("&ORDERAMOUNT=").append(money_).append("&SUBJECT=")
                .append(body)
                .append("&PRODUCTID=").append("04").append("&PRODUCTDESC=").append(body)
                .append("&CUSTOMERID=").append(phone).append("&SWTICHACC=").append("true")
                .append("&KEY=").append(mch_key);

            // 签名
            logger.info("MAC(MD5)--before--String：" + md5Buffer.toString());
            String sign = CryptTool.md5Digest(md5Buffer.toString());
            logger.info("MAC(MD5)--after--String:" + sign);

            // 拼接返回数据串
            StringBuffer paramsBuffer = new StringBuffer();
            paramsBuffer
                .append("SERVICE=")
                .append("mobile.security.pay")
                .append("&MERCHANTID=")
                .append(mch_id)
                // 签约商户号
                .append("&MERCHANTPWD=").append(mch_pwd).append("&SUBMERCHANTID=").append("")
                .append("&BACKMERCHANTURL=").append(callBackUrl).append("&SIGNTYPE=").append("MD5")
                .append("&SIGN=").append(sign).append("&ORDERSEQ=").append(strReq)
                .append("&ORDERREQTRANSEQ=").append(strReq).append("&ORDERTIME=").append(currTime)
                .append("&ORDERVALIDITYTIME=").append("").append("&ORDERAMOUNT=").append(money_)
                .append("&CURTYPE=").append("RMB").append("&PRODUCTID=").append("04")
                .append("&PRODUCTDESC=").append(body).append("&PRODUCTAMOUNT=").append(money_)
                .append("&ATTACHAMOUNT=").append("0.00").append("&ATTACH=").append(attach_order_id)
                .append("&DIVDETAILS=").append("").append("&ACCOUNTID=").append("")
                .append("&CUSTOMERID=").append(phone).append("&USERIP=").append("")
                .append("&BUSITYPE=")
                .append("04").append("&SWTICHACC=").append("true").append("&SUBJECT=").append(body);

            // 返回数据
            String params = paramsBuffer.toString();
            mapData.put("success", false);
            mapData.put("params", params);
        } catch (Exception e) {
            mapData.put("success", false);
            mapData.put("message", "支付接口请求失败");
        }
        return mapData;
    }

    // 翼支付支付后的接口
    @RequestMapping(value = "bestpay/afternotify")
    public synchronized @ResponseBody
    String bestpayAfterNotify(HttpServletResponse response,
        HttpServletRequest request) throws UnsupportedEncodingException {

        try {
            // 准备
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();

            // 获取回调数据，注释部分为没有使用的部分数据，其所代表的意义详见翼支付APP文档
            String UPTRANSEQ = request.getParameter("UPTRANSEQ");
            String MERCHANTID = request.getParameter("MERCHANTID");
            String TRANDATE = request.getParameter("TRANDATE");
            String RETNCODE = request.getParameter("RETNCODE");
            String RETNINFO = request.getParameter("RETNINFO");
            // String ORDERREQTRANSEQ = request.getParameter("ORDERREQTRANSEQ");
            String ORDERSEQ = request.getParameter("ORDERSEQ");
            String ORDERAMOUNT = request.getParameter("ORDERAMOUNT");
            // String PRODUCTAMOUNT = request.getParameter("PRODUCTAMOUNT");
            // String ATTACHAMOUNT = request.getParameter("ATTACHAMOUNT");
            // String CURTYPE = request.getParameter("CURTYPE");
            // String ENCODETYPE = request.getParameter("ENCODETYPE");
            // String BANKID = request.getParameter("BANKID");
            String ATTACH = request.getParameter("ATTACH");
            // String UPREQTRANSEQ = request.getParameter("UPREQTRANSEQ");
            // String UPBANKTRANSEQ = request.getParameter("UPBANKTRANSEQ");
            // String PRODUCTNO = request.getParameter("PRODUCTNO");
            String SIGN = request.getParameter("SIGN");

            // 验证签名
            Setting setting = settingUtils.get();
            String key = setting.getMerKey();
            String signStr = "UPTRANSEQ=" + UPTRANSEQ + "&MERCHANTID=" + MERCHANTID + "&ORDERSEQ="
                + ORDERSEQ + "&ORDERAMOUNT=" + ORDERAMOUNT + "&RETNCODE=" + RETNCODE + "&RETNINFO="
                + RETNINFO + "&TRANDATE=" + TRANDATE + "&KEY=" + key;
            String localSign = CryptTool.md5Digest(signStr);

            // 验签失败
            if (!localSign.equals(SIGN)) {
                out.write("UPTRANSEQ_" + UPTRANSEQ);
                logger.info("支付回调，验签失败！");
                return "fail";
            }

            // 验签成功，看是否支付成功("0000为成功，其他均为失败")
            if (RETNCODE.equals("0000")) {

                // 调用货运系统支付成功
                Long orderId = Long.valueOf(ATTACH.split("_")[2]);
                PayRecordOrder payRecordOrder = freightService.findOnePayRecordOrder(orderId);
                if (payRecordOrder.isTreatment()) {
                    return "success";
                }

                Order order = freightService.findOne(payRecordOrder.getOrderId());

                if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                    return "success";
                }

                Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
                Driver driver = driverService.findOne(order.getEmployId());

                Result<Order> result = freightService.completeTaskNewV3(order, passenger, driver,
                    "onlinePay", "bestpay");

                if (result.isSuccess()) {

                    Result<PayRecordOrder> result2 = freightService
                        .payRecordOrderTreatment(payRecordOrder);

                    if (result2.isSuccess()) {

                        OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(
                            driver, order.getId(), "freight");
                        applicationEventMulticaster.multicastEvent(orderPassengerHasPayEvent);

                        return "success";
                    } else {
                        return "fail";
                    }

                } else {
                    return "fail";
                }
            }
            return "fail";
        } catch (Exception e) {
            // 异常不返回，以便不丢失支付数据
            e.printStackTrace();
            return "fail";
        }

    }

}
